import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Evaluate {
  public static void main(String[] args) {
    Stack<String> ops = new Stack<String>();
    Stack<Double> vals = new Stack<Double>();
    StdOut.println("请输入表达式:");
    while (!StdIn.isEmpty()) {
      String s = StdIn.readString();
      if (s.equals("(")) { // 如果是左括号不操作

      } else if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("sqrt")) { // 如果是操作符则压入操作符栈
        ops.push(s);
      } else if (s.equals(")")) { // 如果是右括号则弹出运算符和操作数并计算结果
        String op = ops.pop();
        Double val = vals.pop();
        if (op.equals("+"))
          val = vals.pop() + val;
        else if (op.equals("-"))
          val = vals.pop() - val;
        else if (op.equals("*"))
          val = vals.pop() * val;
        else if (op.equals("/"))
          val = vals.pop() / val;
        else if (op.equals("sqrt"))
          val = Math.sqrt(val);
        vals.push(val);
      } else {
        vals.push(Double.parseDouble(s));
      }

    }
    System.out.println(vals.pop());
  }
}
